package br.com.tccallan.dao;

import java.security.NoSuchAlgorithmException;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;


import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import br.com.tccallan.encripty.Encripty;
import br.com.tccallan.entity.Usuario;

public class UsuarioDAO extends DAO {

	private static UsuarioDAO instance;

	public static UsuarioDAO getInstance() {
		if (instance == null) {
			instance = new UsuarioDAO();
		}
		return instance;
	}

	public Usuario autentica(Usuario usuario) throws NoSuchAlgorithmException {
		HibernateUtility.beginTransaction();
		Criteria c = HibernateUtility.getSession().createCriteria(Usuario.class);
		c.add(Restrictions.eq("siape", usuario.getSiape()));
		c.add(Restrictions.eq("senha",Encripty.criptografaSenha(usuario.getSenha())));
		HibernateUtility.commitTransaction();
		return (Usuario) c.uniqueResult();
	}

	public void save(Object objeto) {
		try {
			HibernateUtility.getSession().clear();
			HibernateUtility.beginTransaction();
			HibernateUtility.getSession().save(objeto);
			HibernateUtility.commitTransaction();
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
					"Item salvo com sucesso!", "Item salvo com sucesso!");
			FacesContext.getCurrentInstance().addMessage("", message);
		} catch (Exception e) {
			HibernateUtility.rollbackTransaction();
			FacesMessage message = new FacesMessage(
					FacesMessage.SEVERITY_ERROR,
					"Erro ao comunicar com o servidor!",
					"Erro ao comunicar com o servidor!");
			FacesContext.getCurrentInstance().addMessage("", message);
		}
	}
}
